package com.crack.cracktool;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SearchView;
import android.widget.Toast;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by lyh on 2018/4/23.
 */

public class MainAcitity extends AppCompatActivity {

    double  yun =0;
    private PopupWindow popupWindow;
    private ListView mainListView, popupListView;
    private String[] mainListData = {"选项1", "选项2", "选项3"};
    private List<String> datas = new ArrayList<>();
    private String[] dataa= new String[1];
    private File adc = new File("/sdcard/hookLua/2494");
    private HashMap<String,String>  map=new HashMap<String ,String>();
    private String[] tmp= new String[1];
    private String[] tmp2= new String[1];
    private void writeDataToFile(String data, File file) throws IOException {
        FileWriter writer = new FileWriter(file, true);
        writer.write(data);
        writer.close();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.yun=999d;

        setContentView(R.layout.main_acitity);


        try {

            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open("a"),"UTF-8");
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            StringBuffer Result=new StringBuffer();
            while((line = bufReader.readLine()) != null)
            {
                Result.append(line);
            }
            String text = Result.toString();
                                JSONObject jobj = new JSONObject(text);
            Iterator<String> keys = jobj.keys();  //获取所有的Key
            while (keys.hasNext()) {  //循环遍历所有的key
                String key = keys.next();  //获取当前key
                //你的操作
                JSONObject kk =  jobj.getJSONObject(key);
                String name =kk.getString("name");
                if(name !=null && name!=""){
                    map.put(name,key);
                    datas.add(name);
                }


            }
            dataa=datas.toArray(dataa);
            tmp=datas.toArray(tmp);
            tmp2=datas.toArray(tmp2);
            String name = jobj.getJSONObject("108501").getString("name");
            System.out.println(name);
        }catch (Exception e){
            e.printStackTrace();
        }




        final  LinearLayout popupLayout = new LinearLayout(MainAcitity.this);

        mainListView = findViewById(R.id.main_list_view);
        popupListView = new ListView(this);
        final SearchView searchView = findViewById(R.id.search_view);
        final AtomicBoolean init= new AtomicBoolean(false);


        ArrayAdapter<String> mainListAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataa);

        mainListView.setAdapter(mainListAdapter);

        // 设置搜索框监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 在用户点击查询按钮时更新 listview 数据
                List<String> filteredList = new ArrayList<>();
                for (String item : dataa) {
                    if (item.contains(query)) {
                        filteredList.add(item);
                    }
                }
                tmp=filteredList.toArray(tmp);
                ArrayAdapter<String> filteredListAdapter = new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1, filteredList);
                mainListView.setAdapter(filteredListAdapter);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                // 在搜索框文本变化时更新 listview 数据
                List<String> filteredList = new ArrayList<>();
                for (String item : dataa) {
                    if (item.contains(newText)) {
                        filteredList.add(item);
                    }
                }
                tmp=filteredList.toArray(tmp);
                ArrayAdapter<String> filteredListAdapter = new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1, filteredList);
                mainListView.setAdapter(filteredListAdapter);
                return true;
            }
        });


        mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {


                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
//                    popupListView.setAdapter(new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1, new String[]{"弹出选项1", "弹出选项2", "弹出选项3"}));
                    // 在弹出列表时设置列表的背景为透明
//                    popupListView.setBackgroundColor(Color.CYAN);
                    if(init.get() == false) {

                        SearchView searchView = new SearchView(MainAcitity.this);
                        LinearLayout.LayoutParams searchViewLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                        searchView.setLayoutParams(searchViewLayoutParams);


                        searchView.setBackgroundColor(Color.CYAN);

                        // 设置搜索框提示文本
                        searchView.setQueryHint("搜索选项");

                        // 设置搜索框监听器
                        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                            @Override
                            public boolean onQueryTextSubmit(String query) {
                                // 在用户点击查询按钮时更新弹出列表数据
                                List<String> filteredList = new ArrayList<>();
                                for (String item :  dataa) {
                                    if (item.contains(query)) {
                                        filteredList.add(item);
                                    }
                                }
                                tmp2=filteredList.toArray(tmp2);
                                ArrayAdapter<String> filteredListAdapter = new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1, filteredList);
                                popupListView.setAdapter(filteredListAdapter);
                                return true;
                            }

                            @Override
                            public boolean onQueryTextChange(String newText) {
                                // 在搜索框文本变化时更新弹出列表数据
                                List<String> filteredList = new ArrayList<>();
                                for (String item :  dataa) {
                                    if (item.contains(newText)) {
                                        filteredList.add(item);
                                    }
                                }
                                tmp2=filteredList.toArray(tmp2);
                                ArrayAdapter<String> filteredListAdapter = new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1, filteredList);
                                popupListView.setAdapter(filteredListAdapter);
                                return true;
                            }
                        });

                        // 将搜索框添加到 LinearLayout 中，并将 LinearLayout 设置为 popupListView 的头部

                        popupLayout.setOrientation(LinearLayout.VERTICAL);
                        popupLayout.addView(searchView);
                        popupLayout.addView(popupListView);
                        init.set(true);
                    }


//                    popupListView.addHeaderView(popupLayout);

                    popupListView.setAdapter(new ArrayAdapter<>(MainAcitity.this, android.R.layout.simple_list_item_1,  dataa));
                    popupListView.setBackgroundColor(Color.CYAN);


                    popupWindow = new PopupWindow(popupLayout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

                    popupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                        private int pp = position;

                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int positions, long id) {
                            Toast.makeText(MainAcitity.this, "您选择了" + tmp[pp] + ":" + "弹出选项" + tmp2[positions], Toast.LENGTH_SHORT).show();
                            try{
                                writeDataToFile(String.format("\ngd_base_fashion[%s]=gd_base_fashion[%s]",map.get(tmp[pp]).toString(), map.get(tmp2[positions])).toString(),adc);
                            }catch (Exception e){
                                Log.e("8470",e.toString());
                            }
                            popupWindow.dismiss();
                        }
                    });


//                    popupWindow = new PopupWindow(popupListView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

                    popupWindow.setTouchable(true);
                    popupWindow.setBackgroundDrawable(new ColorDrawable());
                    popupWindow.showAsDropDown(view);
                }
            }
        });

    }
}
